import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import permission from './store/modules/permission'
import request from './utils/request'
import { routers } from '@/router/addIndex'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  console.log(hasToken, 'hastoken')
  // const routes = store.state.permission.routes

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      // 判断一下vuex里面有没有动态路由
      // 有的话next()
      // 没有的话调取接口 addRoute next({...to.path})
      // if (hasGetUserInfo && routes.length !== 0) {
      if (hasGetUserInfo && store.state.permission.allRoutes.length != 0) {
        next()
      } else {
        try {
          // get user info
          await store.dispatch('user/getInfo')
          // 数组去重
          // eslint-disable-next-line no-inner-declarations

          // 比较
          const sortArr = (arr) => {
            const tdArr = []
            arr.forEach(ele => {
              routers.forEach(el => {
                if (ele.titles == el.meta.title) {
                  el.pid = ele.pid
                  el.id = ele.id
                  tdArr.push(el)
                }
              })
            })
            return tdArr
          }
          // 请求

          // 递归方法
          const changeTree = (a, k) => {
            const newArray = []
            a.forEach(ele => {
              if (ele.pid == k) {
                newArray.push(ele)
                ele.children = [...changeTree(a, ele.id)]
                // ele.children.push(...changeTree(a, ele.id))
              }
            })
            return newArray
          }
          request.get('/routerAll').then(res => {
            const data = sortArr(res.data)
            const resultArr = changeTree(data, '0')
            const resArr = [...resultArr, { path: '*', redirect: '/404', hidden: true }]
            console.log(resArr, 'resArr')
            store.commit('permission/add_routes', resArr)
            router.addRoutes(store.state.permission.allRoutes)
            // res.data.forEach(ele => {
            //   data.forEach(el => {
            //     if (ele.titles == el.tips) {
            //       newArray.push(el)
            //     }
            //   })
            // })
            // store.commit('permission/add_routes', newArray)
            // router.addRoutes(store.state.permission.allRoutes)
          })

          // store.commit('permission/add_routes', newArray)
          // router.addRoutes(store.state.permission.allRoutes)
          // console.log(store.state.permission.allRoutes)

          // store.commit("permission/ADD_Routes", [
          //   {
          //     path: "/form",
          //     component: Layout,

          //     children: [
          //       {
          //         path: "",
          //         name: "Form",
          //         component: () => import("@/views/form/index"),
          //         meta: { title: "Form", icon: "form", role: ["admin"] },
          //       },
          //     ],
          //   },
          // ]);
          // const routes = [
          //   {
          //     path: '/form',
          //     component: Layout,
          //     children: [
          //       {
          //         path: '',
          //         name: 'Form',
          //         component: () => import('@/views/form/index'),
          //         meta: { title: 'Form', icon: 'form', role: ['admin'] }
          //       }
          //     ]
          //   }
          //   // { path: "*", redirect: "/404", hidden: true },
          // ]

          // /引入变量的方式
          // const str = '@/views/form/index.vue'
          // const routes = [
          //   {
          //     path: '/form',
          //     component: Layout,
          //     children: [
          //       {
          //         path: '',
          //         name: 'Form',
          //         component: (resolve) => require([`${str}`], resolve),
          //         meta: { title: 'Form', icon: 'form', role: ['admin'] }
          //       }
          //     ]
          //   }
          //   // { path: "*", redirect: "/404", hidden: true },
          // ]

          // console.log(routes, "kkll");
          // // const routes = store.state.permission.routes;
          // router.addRoutes(routes);

          // 由于本版本是老版本 addRoutes能用
          // router.addRoutes(routes)

          // 如果是新版
          // addRoute

          // router.addRoutes(routes[1]);
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
